package com.hongmeng.teamwork.domain.impl;

import com.alibaba.fastjson.JSON;
import com.hongmeng.teamwork.convert.UserConvert;
import com.hongmeng.teamwork.domain.IUserDomainService;
import com.hongmeng.teamwork.entity.vo.UserVo;
import com.hongmeng.teamwork.utils.FeishuUtil;
import com.lark.oapi.Client;
import com.lark.oapi.core.request.RequestOptions;
import com.lark.oapi.service.authen.v1.model.GetUserInfoResp;
import com.lark.oapi.service.contact.v3.model.FindByDepartmentUserReq;
import com.lark.oapi.service.contact.v3.model.FindByDepartmentUserResp;
import com.lark.oapi.service.contact.v3.model.User;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Log4j2
@Service
public class UserDomainServiceImpl implements IUserDomainService {

    @Resource
    private Client client;

    @Override
    public List<User> findByDepartment(String accessToken, String departmentId) {
        FindByDepartmentUserResp resp;
        try {
            resp = client.contact().user()
                    .findByDepartment(FindByDepartmentUserReq.newBuilder().departmentId(departmentId).build(),
                            FeishuUtil.getRequestOptionsByAccessToken(accessToken));
        } catch (Exception e) {
            log.error("UserServiceImpl.findByDepartment.error: {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
        List<User> userList = Arrays.asList(resp.getData().getItems());
        if (log.isInfoEnabled()) {
            log.info("UserServiceImpl.findByDepartment.userList: {}", JSON.toJSONString(userList));
        }
        return userList;
    }

    @Override
    public UserVo findLoginUser(String accessToken) {
        GetUserInfoResp resp;
        try {
            resp = client.authen().userInfo()
                    .get(RequestOptions.newBuilder().userAccessToken(accessToken).build());
        } catch (Exception e) {
            log.error("UserServiceImpl.findLoginUser.error: {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
        UserVo userVo = UserConvert.INSTANCE.convertGetUserRespBodyToVo(resp.getData());
        if (log.isInfoEnabled()) {
            log.info("UserServiceImpl.findLoginUser.userVo: {}", JSON.toJSONString(userVo));
        }
        return userVo;
    }
}
